<?php
class Advertisement_Controller extends Template_Controller {
	
	public $search;
	public $template = 'admin/index';
	
    public function __construct()
    {
        parent::__construct();
        
        $this->search = array('keyword' => '','page' => 0,'type'=>'');
        
        $this->_get_submit();
    }
    
	public function __call($method, $arguments)
	{
		// Disable auto-rendering
		$this->auto_render = FALSE;
	}
	
	function _get_submit()
	{
		if($this->session->get('error_msg'))
			$this->template->error_msg = $this->session->get('error_msg');
		if($this->session->get('warning_msg'))
			$this->template->warning_msg = $this->session->get('warning_msg');
		if($this->session->get('success_msg'))
			$this->template->success_msg = $this->session->get('success_msg');
		if($this->session->get('info_msg'))
			$this->template->info_msg = $this->session->get('info_msg');
		if($this->session->get('frm'))			
			$this->template->content->mr = $this->session->get('frm');
	}
	
    public function index()
    {	
        $this->showlist();
    }
    
    public function _show($id='')
	{
		if($id)
			$this->db->where('adv_id',$id);
		$model = new Adv_Model(); 
		$mlist = $model->get();
		return $mlist;
	}
	
    public function showlist()
    {
    	$this->template->content = new View('admin_advertisement/list');
    	//Assign
		$this->template->content->keyword = $this->search['keyword'];
		$this->template->content->type = $this->search['type'];
		$this->where_sql();
		
		//Pagination
    	$this->pagination = new Pagination(array(
    		'base_url'    => 'admin_advertisement',
		    'uri_segment'    => 'page',
		    'total_items'    => ORM::factory('adv')->count_all(),
		    'items_per_page' => $this->site['site_num_line2'],
		    'style'          => 'classic',
		));
		$this->db->limit($this->pagination->items_per_page,$this->pagination->sql_offset);
    	
    	$this->where_sql();
    	$mlist = $this->_show();
    	//print_r($mlist);
    	$this->template->content->mlist = $mlist;
    	
    	$this->_get_submit();
    }
    
    public function where_sql()
    {
    	if($this->search['keyword'])
    		$this->db->like('adv_name',$this->search['keyword']);
		if($this->search['type'])
		$this->db->like('adv_position',$this->search['type']);
    }
    
    public function search()
    {    	
    	//Get    	
    	if($this->session->get('sess_search')){			
			$this->search = $this->session->get('sess_search');
		}
		
		$keyword = $this->input->post('txt_keyword');
		if(isset($keyword)){    		
			$this->search['keyword'] = $keyword;
		}
		$type = $this->input->post('txt_type');
		if(isset($type)){    		
			$this->search['type'] = $type;
		}
		//Page
		$page = $this->uri->segment('page');
		if($page)
			$this->search['page'] = $page;
			
		//Set
		$this->session->set_flash('sess_search',$this->search);
		
		$this->showlist();
    }
    
    public function create()
    {
    	$this->template->content = new View('admin_advertisement/frm');
    	
    }
    
    public function edit($id)
    {	
    	$this->template->content = new View('admin_advertisement/frm');
    	 $list = $this->_show($id);
    	$mr = $list[0];
		$this->template->content->mr = $mr;
    }
    
    private function _get_record()
    {
    	$form = array
	    (
	    	'txt_name' => '',
			'txt_url' => '',
			'txt_begin_date' =>'',
			'txt_expired_date' => '',			
			'txt_position' => '',
			'txt_open' => '',
			'txt_order' => '',
			'txt_status' => '',
			'chk_delfile' => '',
			'hd_old_image' => '',
			
	    );
				
		if($_POST)
    	{
    		$post = new Validation($_POST);
    		
			$post->pre_filter('trim', TRUE);
			$post->add_rules('txt_name','required');
			if($post->validate())
 			{
 				$form = arr::overwrite($form, $post->as_array());
 				return $form; 				
			} else {
				$errors = arr::overwrite($errors, $post->errors('adv_validation'));
				$str_error = '';
	            if ($errors['txt_name'])
						$str_error .= $errors['adv_name'].'<br>';
				}
				$this->session->set_flash('error_msg',$str_error);
				
				$hd_id = $this->input->post('hd_id');
				if($form['hd_id'])
					url::redirect('admin_advertisement/edit/'.$form['hd_id']);
				else
					url::redirect('admin_advertisement/create');
				die();
			}
   }
    
    
    private function _get_image($chk_delete,$hd_old_image)
	{
		//============Check image old=====================	
		if($hd_old_image)
		{
			$path_filedel = './uploads/adv/'.$hd_old_image;
		} 
		else	
			$path_filedel = '';
	
		if($chk_delete)
		{
			if(file_exists($path_filedel)) @unlink($path_filedel);
			
			return '';
		}
		//============Upload==============================	
		// uses Kohana upload helper	
		
		$_FILES = Validation::factory($_FILES)
			->add_rules('attach_1', 'upload::valid', 'upload::type[gif,jpg,png,flv]', 'upload::size[1M]');
			
		if ($_FILES['attach_1']['error']==0)
		{
			//delete file if have upload image
			if(file_exists($path_filedel)) unlink($path_filedel);
			
			Kohana::config_set('upload.directory', DOCROOT.'uploads/adv');
			//$filename = upload::save('txt_import');	
			// Temporary file name
			$filename = upload::save('attach_1');
			// Resize, sharpen, and save the image
			//print_r($_FILES['txt_image']);
			//exit();
			// Redirect back to the account page
			return basename($filename);
		} else {
			if ($hd_old_image)
				return $hd_old_image;
			else
				return '';
		}
	}
    private function _save($hd_id,$record)
    {
		if(!$hd_id){
			$result = ORM::factory('adv');
		} else {
			$result = ORM::factory('adv',$hd_id);
		}
		$result->adv_name = $record['txt_name'];
		$result->adv_url = $record['txt_url'];
		$result->adv_begin_date = $record['txt_begin_date'];
		$result->adv_expired_date = $record['txt_expired_date'];
		$result->adv_position = $record['txt_position'];
		$result->adv_open = $record['txt_open'];
		$result->adv_order = $record['txt_order'];
		$result->adv_status = $record['txt_status'];
		$result->adv_image = $this->_get_image($record['chk_delfile'],$record['hd_old_image']);
		$hd_id = $result->save();
		return $hd_id;
	}
	
	
	
    public function save()
    {
    	$hd_id = $this->input->post('hd_id');
    	
    	$record = $this->_get_record();
		
		if($record)
		{
			$hd_id1 = $this->_save($hd_id,$record);
			if(!$this->input->post('hd_id'))
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_add'));
			else
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
		}
		url::redirect('admin_advertisement/edit/'.$hd_id1);
		die();    	
    }
    
    public function saveall()
    {
    	$arr_id = $this->input->post('chk_id');
		
		if(is_array($arr_id)){
			$sel_action = $this->input->post('sel_action');
		
			if($sel_action == 'delete')	{
				$id = ORM::factory('adv')->delete_all($arr_id);
				if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));
			} elseif($sel_action == 'blocked') {
				foreach($arr_id as $arr => $id){
					$result = ORM::factory('adv',$id);
			    	$result->adv_status = 0;
			    	$id = $result->save();
		    	}
		    	if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
			} elseif($sel_action == 'active')
			{
				foreach($arr_id as $arr => $id){
					$result = ORM::factory('adv',$id);
			    	$result->adv_status = 1;
			    	$id = $result->save();
		    	}
		    	if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
			}			
		} else {
			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));
		}
		url::redirect('admin_advertisement');		
		die();
    }
    
    public function delete($id)
    {
    	$status = $this->db->delete('advertisement',array('adv_id' => $id));
    	if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));
		}
    	url::redirect('admin_advertisement');
    	die();
    }
    
    public function setstatus($id,$status)
    {
    	$status = $this->db->update('advertisement',array('adv_status' => $status),array('adv_id' => $id));
    	if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_status_change'));
		}
    	url::redirect('admin_advertisement'); 
    	die();
    }	
}
?>